package com.gl.course2;

/**
 * Created by GAOLEI on 2019/7/26.
 */
public class FooBar {
    private int n;
    private volatile  int flag = 0;

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
     synchronized (this){
         for (int i = 0; i < n; i++) {
             while (flag%2 == 1){
                 wait();
             }
             flag ++;
             // printFoo.run() outputs "foo". Do not change or remove this line.
             printFoo.run();
             notifyAll();
         }
     }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        synchronized (this){
            for (int i = 0; i < n; i++) {
                while (flag%2 == 0){
                    wait();
                }
                flag ++;
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                notifyAll();
            }
        }
    }
}
